package org.dftproject.pgv.core.racp.factories;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;

import org.dftproject.genesis.core.collections.Collection;
import org.dftproject.genesis.core.collections.CollectionManager;
import org.dftproject.genesis.core.persistence.IMemento;
import org.dftproject.genesis.core.persistence.IPersistenceFactory;
import org.dftproject.pgv.core.racp.PGVGedcom;
import org.dftproject.pgv.core.racp.Session;
import org.dftproject.pgv.core.racp.SessionManager;

public class PGVGedcomFactory implements IPersistenceFactory {

	public static final String ID = PGVGedcomFactory.class.getName();
	
	public Object createObject(IMemento memento) {
		Session session = getSession(memento.getString("url"));
		if (session == null)
			return null;
		return new PGVGedcom(session, memento.getString("gedcomId"));
	}
	
	public static Session getSession(String url) {
		for (Collection collection : CollectionManager.getDefault().getCollections("org.dftproject.pgv")) {
			Properties props = new Properties();
			try {
				props.load(new ByteArrayInputStream(collection.getData().getBytes()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if (url.equals(props.getProperty("url")))
				return SessionManager.getDefault().getSession(props.getProperty("url"), props.getProperty("username"), props.getProperty("password"));
		}
		
		return SessionManager.getDefault().getSession(url);
	}

}
